<template>
    <div>
        <Breadcrumb :style="{margin: '20px 0'}">
            <BreadcrumbItem>终端管理</BreadcrumbItem>
            <BreadcrumbItem>查看历史</BreadcrumbItem>
        </Breadcrumb>
        <div class="table-toolbar">
            <Checkbox v-model="inline" false-value="outline" true-value="inline">只显示在线</Checkbox>
            <ButtonGroup>
                <Button type="primary" @click="getInfo">刷新</Button>
            </ButtonGroup>
        </div>
        <Table :columns="columns" :data="dataList"></Table>
        <div>
            <Page :page-size="page.limit" :total="page.total" simple @on-change="pageChange"/>
        </div>
        <Modal
            v-model="modalShow"
            title="添加手机"
            @on-ok="save">
            <div class="field">
                <div class="label">是否真实终端(真机）</div>
                <Select v-model="phoneInfo.isReal" class="mb-10" value="1">
                    <Option value="1">是</Option>
                    <Option value="0">否</Option>
                </Select>
            </div>
            <div class="field">
                <div class="label">名称</div>
                <Input v-model="phoneInfo.name" class="mb-10" placeholder="名称"/>
            </div>
            <div class="field">
                <div class="label">终端IP地址(如果是虚拟机可以不填）</div>
                <Input v-model="phoneInfo.ip" class="mb-10" placeholder="手机的ip地址"/>
            </div>
            <div class="field">
                <div class="label">
                    设备号(不知道的可以留空)
                </div>
                <Input v-model="phoneInfo.device" class="mb-10" placeholder="设备号(不知道的可以留空)"/>
            </div>
            <div class="field">
                <div class="label">
                    连接终端的端口（必选，并且唯一)
                </div>
                <Select v-model="phoneInfo.port" class="mb-10">
                    <Option v-for="item in portList" :key="item.value" :value="item.value">{{ item.label }}</Option>
                </Select>
            </div>
        </Modal>
        <Modal
            v-model="fileListModel"
            title="文件列表">
            <template v-for="(value,index) in fileList">
                <div :key="value" class="item-list" @click="selectDirectionPath(index,type)">{{ value }}</div>
            </template>
        </Modal>
    </div>
</template>

<script>
import adb from '../util/adb'
import model from '../util/model'

let process = require('child_process')

export default {
    name: 'DeviceScan',
    data: function () {
        return {
            phoneInfo: {
                name: '',
                ip: '',
                device: '',
                port: null,
                pic: '',
                radio: '',
                isReal: 1
            },
            inline: 1,
            modalShow: false,
            portList: [],
            page: {
                limit: 20,  //列表分页
                skip: 0,
                total: 0,
                oldPage: 1
            },
            columns: [
                {
                    title: '/',
                    render: (h, p) => {
                        return h('div', {
                            style: {
                                width: '45px'
                            },
                        }, p.row._index)
                    }
                },
                {
                    title: '名称',
                    key: 'name'
                },
                {
                    title: '设备号',
                    key: 'device'
                },
                {
                    title: 'ip',
                    key: 'ip'
                },
                {
                    title: '端口',
                    key: 'port'
                },
                {
                    title: '图片地址',
                    key: 'pic',
                    render: (h, params) => {
                        return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'default',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.setPicturePath(params.index)
                                        }
                                    }
                                }, params.row.pic ? params.row.pic : '设置')
                            ]
                        )
                    }
                },
                {
                    title: '视频地址',
                    key: 'radio',
                    render: (h, params) => {
                        return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    on: {
                                        click: () => {
                                            this.setRadioPath(params.index)
                                        }
                                    }
                                }, params.row.radio ? params.row.radio : '设置')
                            ]
                        )
                    }
                },
                {
                    title: '操作',
                    key: 'action',
                    width: 300,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small',
                                    disabled: params.startWirelessLink
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.startServer(params.index)
                                    }
                                }
                            }, '开启'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.editInfo(params.index)
                                    }
                                }
                            }, '修改'),

                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.remove(params.index)
                                    }
                                }
                            }, '删除'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    margin: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.removePic(params.index)
                                    }
                                }
                            }, '删除某项数据')
                        ])
                    }
                }
            ],
            dataList: [],
            isLinking: [],
            fileListModel: false,
            fileList: [],
            activeTableIndex: null,
            type: 1
        }
    },
    created: function () {
        this.getInfo()

    },
    watch: {
        inline: function (value) {
            if (value) {
                this.getInfo()
            }
        }
    },
    methods: {
        getInfo: async function () {
            let that = this
            if (this.inline === 'inline') {
                let newStdout = []
                let deviceArr = []
                let valueTemp = ''
                let valueTemp2 = ''
                let deviceList = []
                let item = {
                    device: ''
                }
                process.exec('adb devices', {timeout: 5000}, function (error, stdout, stderr) {
                    if (stdout) {
                        newStdout = stdout.split('\n')
                        deviceArr = newStdout.slice(1, -1)
                        if (deviceArr.length > 0) {
                            let testValue = deviceArr[0].replace(/[\r\n]*/g, '')
                            if (testValue !== '') {
                                deviceArr.forEach((value, index) => {
                                    valueTemp2 = value.replace(/[\r\n]*/g, '')
                                    if (valueTemp2 !== '') {
                                        valueTemp = valueTemp2.split('\t')
                                        item = {}
                                        item.device = valueTemp[0]
                                        deviceList[index] = (item)
                                    }
                                })
                            }
                        }
                        model.info.count({$or: deviceList}, (err, total) => {
                            that.page.total = total
                        })
                        model.info.find({$or: deviceList}).skip(that.page.skip).limit(that.page.limit).exec((err, doc) => {
                            if (doc.length > 0) {
                                doc.forEach((value, index) => {
                                    let temp = {
                                        startWirelessLink: false
                                    }
                                    value = Object.assign(value, temp)
                                })
                                that.dataList = doc
                            } else {
                                that.dataList = []
                            }
                        })
                    }
                })
            } else {
                model.info.count({}, (err, total) => {
                    that.page.total = total
                })
                model.info.find({}).skip(this.page.skip).limit(this.page.limit).exec((err, doc) => {
                    if (doc.length > 0) {
                        doc.forEach((value, index) => {
                            let temp = {
                                startWirelessLink: false
                            }
                            value = Object.assign(value, temp)
                        })
                        that.dataList = doc
                    }
                })
            }
        }
        ,
        pageChange: function (page) {
            this.page.skip = this.page.limit * page - this.page.limit
            this.getInfo()
        }
        ,
        editInfo (index) {
            this.phoneInfo = this.dataList[index]
            this.getPortData()
            this.modalShow = true
        }
        ,
        async startServer (index) {
            let that = this
            let command = 'adb -s ' + this.dataList[index].device + ' tcpip ' + this.dataList[index].port
            await process.exec(command, {timeout: 3000}, function (error, stdout, stderr) {
                if (stdout.indexOf('restarting') !== -1) {
                    command = 'adb connect ' + that.dataList[index].ip + ':' + that.dataList[index].port
                    process.exec(command, {timeout: 3000}, function (error, stdout) {
                        if (stdout.indexOf('connected') !== -1) {
                            that.isLinking[index] = true
                            that.$Message.info('连接成功，可以拔掉USB线了')
                        } else {
                            that.$Message.info('连接出错，请重试')
                        }
                    })
                } else {
                    that.$Message.info('请重试')
                }
            })
        }
        ,
        killServer: function () {
            adb.killServer()
            adb.startServer()
        }
        ,
        remove (index) {
            let that = this
            if (index) {
                let id = this.dataList[index]._id
                model.info.remove({_id: id}, {}, (err, numRemoved) => {
                    if (numRemoved) {
                        that.$Message.info('删除成功')
                        that.getInfo()
                    }
                })
            }
        }
        ,
        getPortData: function () {
            let that = this
            let item = {
                value: 5556,
                label: 5656
            }
            let start = 5556
            let end = 5656
            let temp = []
            model.port.find({}, function (err, cet) {
                start = parseInt(cet[0].start)
                end = parseInt(cet[0].end)
                for (let i = start; i < end; i++) {
                    item = {}
                    item.value = i
                    item.label = i
                    temp.push(item)
                }
            })
            that.portList = temp
        }
        ,
        save: function () {
            let that = this
            model.info.find({device: this.phoneInfo.device}, function (err, docs) {
                if (docs.length === 0) {
                    model.info.insert(that.phoneInfo, function (err, newDoc) {
                        if (newDoc) {
                            that.$Message.info('添加成功')
                        }
                    })
                } else {
                    model.info.update({device: that.phoneInfo.device}, {$set: that.phoneInfo}, {multi: true}, function (err, newDoc) {
                        if (newDoc) {
                            that.$Message.info('修改成功')
                        }
                    })
                }
            })
        }
        ,
        setPicturePath: function (index) {
            // if(this.isLinking[index]){
            let that = this
            this.type = 1
            let command = 'adb -s '
            let port = this.dataList[index].port
            let device = this.dataList[index].device
            this.activeTableIndex = index
            let directList = []
            command = command + device + ' shell ls -l /storage/emulated/0'
            process.exec(command, (error, stdout, stderr) => {
                if (stdout) {
                    let arr = stdout.split('\n')
                    let arr2 = arr.slice(1, -1)
                    if (arr2.length > 0) {
                        arr2.forEach((value, index) => {
                            if (value[0] === 'd') {
                                let temp = value.split(' ')
                                directList.push(temp[temp.length - 1])
                                that.fileList = directList
                                that.fileListModel = true
                            }
                        })
                    }
                }
            })
            // }
        }
        ,
        selectDirectionPath: function (index, type) {
            let that = this
            let directionPath = '/storage/emulated/0/' + this.fileList[index]
            let device = this.dataList[this.activeTableIndex].device
            if (type === 1) {
                model.info.update({device: device}, {$set: {pic: directionPath}}, {multi: true}, function (err, newDoc) {
                    if (newDoc) {
                        that.$Message.info('设置成功')
                        // that.dataList[that.activeTableIndex].pic = directionPath
                        that.$set(that.dataList[that.activeTableIndex], 'pic', directionPath)
                        that.fileListModel = false
                    }
                })
            } else {
                model.info.update({device: device}, {$set: {radio: directionPath}}, {multi: true}, function (err, newDoc) {
                    if (newDoc) {
                        that.$Message.info('设置成功')
                        that.$set(that.dataList[that.activeTableIndex], 'radio', directionPath)
                        that.fileListModel = false
                    }
                })
            }
        }
        ,
        setRadioPath: function (index) {
            // if(this.isLinking[index]){
            let that = this
            this.type = 2
            let command = 'adb -s '
            let port = this.dataList[index].port
            let device = this.dataList[index].device
            this.activeTableIndex = index
            let directList = []
            command = command + device + ' shell ls -l /storage/emulated/0'
            process.exec(command, (error, stdout, stderr) => {
                if (stdout) {
                    let arr = stdout.split('\n')
                    let arr2 = arr.slice(1, -1)
                    if (arr2.length > 0) {
                        arr2.forEach((value, index) => {
                            if (value[0] === 'd') {
                                let temp = value.split(' ')
                                directList.push(temp[temp.length - 1])
                                that.fileList = directList
                                that.fileListModel = true
                            }
                        })
                    }
                }
            })
            // }
        }
        ,
        removePic: function (index) {
            let that = this
            let device = this.dataList[index].device
            model.info.update({device: device}, {$set: {pic: ''}}, {multi: true}, function (err, newDoc) {
                if (newDoc) {
                    that.$Message.info('设置成功')
                }
            })
        }
    }
}
</script>

<style scoped>
.table-toolbar {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    margin-bottom: .2rem;
    padding: 8px 8px;
}

.field {
    margin-bottom: 10px;
}

.label {
    margin-bottom: 5px;
    color: #424242
}

.mb-10 {
    margin-bottom: 10px;
}

.item-list {
    padding: 3px;
    border-bottom: 1px solid #8ebbe8;
    cursor: pointer;
}

.item-list:hover {
    background-color: #b4b4f3;
}
</style>
